package com.example.controller.web;

import com.example.entity.chat.Message;
import com.example.entity.user.User;
import com.example.repository.MessageRepository;
import com.example.repository.UserRepository;
import com.example.service.OllamaService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ChatController {

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OllamaService ollamaService;

    //获取指定用户之间的聊天记录
    @GetMapping("/api/messages")
    public List<Message> getMessages(
            @RequestParam String from,
            @RequestParam String to){
        return messageRepository.findBySenderOrReceiver(from,to);
    }

    @GetMapping("/api/messages/search")
    public ResponseEntity<List<User>> searchUsers(@RequestParam String keyword){
        List<User> users=userRepository.findByUsernameContaining(keyword);
        return ResponseEntity.ok(users);
    }

    @GetMapping("/api/message/history")
    public List<Message> getHistoryMessages(@RequestParam String sender, @RequestParam String receiver) {
        System.out.println("历史发送:"+sender+" 历史接收:"+receiver);
        return messageRepository.findBySenderAndReceiverOrReceiverAndSender(sender, receiver);
    }

    public ChatController(OllamaService ollamaService) {
        this.ollamaService = ollamaService;
    }

    @PostMapping("/api/ollama/deepseek")
    public String chat(@RequestBody Map<String, String> request) {
        String message = request.get("message");
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String cleanedResponse = ollamaService.generateResponse(message)
                    .map(response -> response.replaceAll("<think>\\s*</think>", "").trim())
                    .timeout(Duration.ofSeconds(30))
                    .onErrorReturn("Internal Server Error")
                    .block();
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("message", cleanedResponse);
            String result = objectMapper.writeValueAsString(resultMap);
            System.out.println("我是回复:" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"error\": \"Internal Server Error\"}";
        }
    }

}
